import {Buffer} from 'buffer'
export function mergeConfig(config, defaultConfig) {
  let res = {}
  for (let i in defaultConfig) {
    res[i] = i in config ? config[i] : defaultConfig[i]
  }
  return res
}

export function writeInt(buffer, start, length, value) {
  let i = 0
  while (i < length) {
    buffer[start + i] = value / 256 ** (length - i - 1)
    i++
  }
}

export function encode(string, op) {
  const textEncoder = new TextEncoder()
  const data = textEncoder.encode(string)
  const packetLen = 16 + data.byteLength
  const header = [0, 0, 0, 0, 0, 16, 0, 1, 0, 0, 0, op, 0, 0, 0, 1]
  writeInt(header, 0, 4, packetLen)
  return new Uint8Array(header.concat(...data)).buffer
}

// 生成鉴权包
export function generateCertificate(roomId, token, _uid, buvid) {
  // console.log("generateCertificate", roomId, token, _uid, buvid);
    const headerLength = 16;
    const protocol = 1;
    const type = 7;
    const sequence = 2;
    const body = JSON.stringify({
        uid: Number(_uid),
        roomid: roomId,
        protover: 3, // 这里协议版本一定要是 2，否则无法解析数据！哭，3 还不行
        buvid: buvid,
        platform: 'web',
        type: 2,
        key: token,
    });

    console.log("authBody", body);

    const bodyBuffer = Buffer.from(body);
    const headerBuffer = Buffer.alloc(headerLength);
    headerBuffer.writeUInt32BE(headerLength + bodyBuffer.length, 0);
    headerBuffer.writeUInt16BE(headerLength, 4);
    headerBuffer.writeUInt16BE(protocol, 6);
    headerBuffer.writeUInt32BE(type, 8);
    headerBuffer.writeUInt32BE(sequence, 12);

    return Buffer.concat([headerBuffer, bodyBuffer]);
}

export function getCertification(json){
	let encoder = new TextEncoder();    //编码器
	let jsonView = encoder.encode(json);    //utf-8编码
	let buff = new ArrayBuffer(jsonView.byteLength + 16);    //数据包总长度：16位头部长度+bytes长度
	let view = new DataView(buff);    //新建操作视窗
	view.setUint32(0, jsonView.byteLength + 16);    //整个数据包长度
	view.setUint16(4, 16);    //头部长度
	view.setUint16(6, 1);    //协议版本
	view.setUint32(8, 7);    //类型,7为加入房间认证
	view.setUint32(12, 1);    //填1
	for(let r = 0; r < jsonView.byteLength; r++){
	    view.setUint8(16 + r, jsonView[r]);    //填入数据
	}
  // console.log("auth", buff.toString('hex').match(/.{1,32}/g)?.join('\n'));
	return buff;
}

export function toBool(val) {
  if (typeof val === 'string') {
    return ['false', 'no', 'off', '0', ''].indexOf(val.toLowerCase()) === -1
  }
  return Boolean(val)
}

export function toInt(val, _default) {
  let res = parseInt(val)
  if (isNaN(res)) {
    res = _default
  }
  return res
}

export function toFloat(val, _default) {
  let res = parseFloat(val)
  if (isNaN(res)) {
    res = _default
  }
  return res
}

export function formatCurrency(price) {
  return new Intl.NumberFormat('zh-CN', {
    minimumFractionDigits: price < 100 ? 2 : 0
  }).format(price)
}

export function getTimeTextHourMin(date) {
  let hour = date.getHours()
  let min = `00${date.getMinutes()}`.slice(-2)
  return `${hour}:${min}`
}

export function getUuid4Hex() {
  let chars = []
  for (let i = 0; i < 32; i++) {
    let char = Math.floor(Math.random() * 16).toString(16)
    chars.push(char)
  }
  return chars.join('')
}

export function getUuid8hex() {
  let chars = []
  for (let i = 0; i < 8; i++) {
    let char = Math.floor(Math.random() * 16).toString(16)
    chars.push(char)
  }
  return chars.join('')
}
